//
//  TMDataRequest.m
//  复合发行4.0
//
//  Created by liubowen on 2017/8/30.
//  Copyright © 2017年 Beijing TMYK Technology co.,ltd. All rights reserved.
//

#import "TMDataRequest.h"
#import "HBPAPIRequestSerializer.h"
#import "RTJSONResponseSerializerWithData.h"
#import "SVProgressHUD.h"
#import "UIAlertController+SPAlert.h"
typedef void (^SuccessBlock) (NSURLSessionDataTask *task, id responseObject);
typedef void (^ErrorBlock)   (NSInteger status, NSString * errorMessage);
typedef void (^FailureBlock) (NSURLSessionDataTask *task, NSError *error);

NSString *const TMConnectionChanged = @"ConnectionChanged";

@interface TMDataRequest (){
}
@property (nonatomic,strong) AFHTTPSessionManager *manager;

@end


@implementation TMDataRequest

- (instancetype)init{
    if (self = [super init]){
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        //设置我们的缓存大小 其中内存缓存大小设置10M  磁盘缓存5M
        NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:10 * 1024 * 1024
                                                          diskCapacity:50 * 1024 * 1024
                                                              diskPath:nil];
        [config setURLCache:cache];
        self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:TMAPI_HostName] sessionConfiguration:config];
        
        //请求参数序列化类型
        self.manager.requestSerializer = [HBPAPIRequestSerializer serializer];
        
        // 设置接受解析的内容类型
        self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/json",@"text/plain",@"text/javascript",@"application/json", nil];
        //响应结果序列化类型
        //        self.manager.responseSerializer = [RTJSONResponseSerializerWithData serializer];
        [self AFNetworkStatus];
       // [self dispalyRMStatus];
    }
    return self;
}
+ (TMDataRequest *)defaultRequest{
    static TMDataRequest *request = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        request = [[self alloc]init];
    });
    return request;
}
//HTTP请求（默认GET方式和默认接口文件地址，默认请求前预处理）带加载HUD
- (void)requestWithParam:(id)parameters
                 success:(void (^)(NSURLSessionDataTask *, id))success
                   error:(void (^)(NSInteger, NSString *))error
                 failure:(void (^)(NSURLSessionDataTask *, NSError *))failure{
    
    [SVProgressHUD showWithStatus:@"加载中...."];
    SuccessBlock success_block = ^(NSURLSessionDataTask *  task, id responseObject){
        [SVProgressHUD dismiss];
        success(task,responseObject);
    };
    ErrorBlock error_block = ^(NSInteger status, NSString * errorMessage){
        [SVProgressHUD dismiss];
        error(status,errorMessage);
    };
    FailureBlock failure_block = ^(NSURLSessionDataTask *task, NSError * error){
        [SVProgressHUD dismiss];
        failure(task,error);
    };
    
    [self requestWithParam:parameters prepareExecute:nil success:success_block error:error_block failure:failure_block];
}
//HTTP请求（默认GET方式和默认接口文件地址，默认请求前预处理）不带加载HUD
- (void)requestNoHUDWithParam:(id)parameters
                      success:(void (^)(NSURLSessionDataTask *, id))success
                        error:(void (^)(NSInteger, NSString *))error
                      failure:(void (^)(NSURLSessionDataTask *, NSError *))failure{
    [self requestWithParam:parameters prepareExecute:nil success:success error:error failure:failure];
}


//HTTP请求（默认GET方式和默认接口文件地址）
- (void)requestWithParam:(id)parameters
          prepareExecute:(PrepareExecuteBlock)prepare
                 success:(void (^)(NSURLSessionDataTask *, id))success
                   error:(void (^)(NSInteger, NSString *))error
                 failure:(void (^)(NSURLSessionDataTask *, NSError *))failure{
    [self requestWithPath:TMAPI_BaseFilePath parameters:parameters method:TMDataRequestTypeGet prepareExecute:prepare success:success error:error failure:failure];
    
}

//HTTP请求（GET、POST、DELETE、PUT）
- (void)requestWithPath:(NSString *)urlSting
             parameters:(id)parameters
                 method:(NSInteger)method
         prepareExecute:(PrepareExecuteBlock)prepare
                success:(void (^)(NSURLSessionDataTask *, id))success
                  error:(void (^)(NSInteger, NSString *))error
                failure:(void (^)(NSURLSessionDataTask *, NSError *))failure{
    //http://www.guo.com/api/pub/set_phone_verify
    if (prepare) {
        prepare();
    }else{
        
    }
    switch (method) {
        case TMDataRequestTypeGet:
        {
             NSLog(@"接口地址:\n%@",[NSString stringWithFormat:@"%@%@%@%@",TMAPI_HostName,TMAPI_BaseFilePath,urlSting,parameters]);
            
            [self.manager GET:[NSString stringWithFormat:@"%@%@%@",TMAPI_HostName,TMAPI_BaseFilePath,urlSting] parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    if ([responseObject[@"code"] integerValue] == 200) {
                        success(task, responseObject);
                    }else{

                        error([responseObject[@"code"] integerValue],responseObject[@"msg"]);
                    }
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                failure(task, error);
            }];
            
        }
            break;
        case TMDataRequestTypePost:
        {
            NSLog(@"接口地址:\n%@",[NSString stringWithFormat:@"%@%@%@%@",TMAPI_HostName,TMAPI_BaseFilePath,urlSting,parameters]);
            [TMProgressHUD showWithStatus:@"加载中..."];
            [self.manager POST:[NSString stringWithFormat:@"%@%@%@",TMAPI_HostName,TMAPI_BaseFilePath,urlSting] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
                [TMProgressHUD dismiss];
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    if ([responseObject[@"code"] integerValue] == 200) {
                        success(task, responseObject);
                    }else{
                        
                        error([responseObject[@"code"] integerValue],responseObject[@"msg"]);
                        if ([responseObject[@"msg"] isEqualToString:@"token有误"]) {
                       // SHOW_LOGIN_ALERT;
                        }
                    }
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
                NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"服务器的错误原因:%@",str);
                failure(task, error);
                [TMProgressHUD dismiss];
            }];
        }
            break;
        case TMDataRequestTypeDelete:
        {
            [self.manager DELETE:urlSting parameters:nil success:success failure:failure];
        }
            break;
        case TMDataRequestTypePut:
        {
            [self.manager PUT:urlSting parameters:nil success:success failure:failure];
        }
            break;
            
        default:
            break;
    }
    
    
}

- (void)AFNetworkStatus {
    
    //1.创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    /*枚举里面四个状态  分别对应 未知 无网络 数据 WiFi
     typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
     AFNetworkReachabilityStatusUnknown          = -1,      未知
     AFNetworkReachabilityStatusNotReachable     = 0,       无网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,       蜂窝数据网络
     AFNetworkReachabilityStatusReachableViaWiFi = 2,       WiFi
     };
     */
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //这里是监测到网络改变的block  可以写成switch方便
        //在里面可以随便写事件
        switch (status) {
            case -1:
                NSLog(@"未知网络状态");
                [TMDataRequest defaultRequest].isConnectionEnable = YES;
                [TMDataRequest defaultRequest].isWWANEnable = NO;
                [TMDataRequest defaultRequest].isWifiEnable = NO;
                [TMDataRequest defaultRequest].connectionUnknown = YES;
                break;
            case 0:
                NSLog(@"无网络");
                [SVProgressHUD showInfoWithStatus:@"网络连接已断开"];
                [TMDataRequest defaultRequest].isConnectionEnable = NO;
                [TMDataRequest defaultRequest].isWWANEnable = NO;
                [TMDataRequest defaultRequest].isWifiEnable = NO;
                [TMDataRequest defaultRequest].connectionUnknown = NO;
                break;
                
            case 1:
                NSLog(@"蜂窝数据网");
                [TMDataRequest defaultRequest].isConnectionEnable = YES;
                [TMDataRequest defaultRequest].isWWANEnable = YES;
                [TMDataRequest defaultRequest].isWifiEnable = NO;
                [TMDataRequest defaultRequest].connectionUnknown = NO;
                [[NSNotificationCenter defaultCenter]postNotificationName:TMConnectionChanged object:@"WWAN"];
                break;
                
            case 2:
                NSLog(@"WiFi网络");
                [TMDataRequest defaultRequest].isConnectionEnable = YES;
                [TMDataRequest defaultRequest].isWWANEnable = NO;
                [TMDataRequest defaultRequest].isWifiEnable = YES;
                [TMDataRequest defaultRequest].connectionUnknown = NO;
                [[NSNotificationCenter defaultCenter]postNotificationName:TMConnectionChanged object:@"WiFi"];
                break;
                
            default:
                break;
        }
        
    }] ;
    [manager startMonitoring];
}
#pragma mark -- POST请求 --
- (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
                  success:(void (^)(id))success
                  failure:(void (^)(NSError *))failure {

    [self.manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}


@end
